package com.ruoyi.web.controller.warning;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.warning.domain.entity.DevicesType;
import com.ruoyi.warning.domain.entity.Property;
import com.ruoyi.warning.service.IDevicesTypeService;
import com.ruoyi.warning.service.IPropertyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenhc
 * @since 2025-08-06
 */
@RestController
@RequestMapping("/devicesType")
@Api(tags = "设备类型", description = "用于设备类型处理相关操作的控制器")
public class DevicesTypeController {
    @Resource
    private IDevicesTypeService devicesTypeService;
    @Resource
    private IPropertyService propertyService;
    @ApiOperation("树")
    @Log(title = "树查询", businessType = BusinessType.SELECT)
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @GetMapping(value = "/tree")
    public R tree()
    {
        return R.ok(devicesTypeService.tree());
    }

    @ApiOperation("新增或修改")
    @Log(title = "新增或修改", businessType = BusinessType.UPDATE)
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @PostMapping(value = "/saveOrUpdate")
    public R saveOrUpdate(@RequestBody DevicesType devicesType)
    {
        if(ObjectUtils.isNotEmpty(devicesType.getTypeId())){
            DevicesType old = devicesTypeService.getById(devicesType.getTypeId());
            if(!old.getTypeName().equals(devicesType.getTypeName())){
                //找到所有的同名类型，并统一修改
                List<Property> list = propertyService.list(new LambdaQueryWrapper<>(Property.class)
                        .eq(Property::getDeviceType, old.getTypeName()));
                for (Property property : list){
                    property.setDeviceType(devicesType.getTypeName());
                }
                propertyService.updateBatchById(list);
            }
        }
        return R.ok(devicesTypeService.saveOrUpdate(devicesType));
    }

    @ApiOperation("查看详情")
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @GetMapping(value = "/detail/{id}")
    public R detail(@PathVariable String id)
    {
        return R.ok(devicesTypeService.getById(id));
    }

    @ApiOperation("删除")
    @Log(title = "删除", businessType = BusinessType.DELETE)
    //@PreAuthorize("@ss.hasPermi('system:config:export')")
    @DeleteMapping(value = "/delete/{id}")
    public R delete(@PathVariable String id)
    {
        return R.ok(devicesTypeService.removeById(id));
    }
}
